﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Microsoft.WebMatrix.Extensibility;

namespace BuildnDeploy {
    [Serializable]
    public class Settings {
        public string BuildCommand { get; set; }
        public string DeployCommand { get; set; }
        string _myFilename;

        public static Settings LoadForWebsite(IWebSite website) {
            string settingsFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "BnDCache", website.Name + ".xml");
            Settings s = new Settings() {
                BuildCommand = string.Format("{0}\\build.cmd", website.Path),
                DeployCommand = string.Format("{0}\\deploy.cmd", website.Path)
            };
            s._myFilename = settingsFilePath;
            if (!File.Exists(settingsFilePath)) {
                try {
                    XmlSerializer x = new XmlSerializer(typeof(Settings));
                    using (StreamWriter sw = new StreamWriter(settingsFilePath)) {
                        x.Serialize(sw, s);
                    }
                }
                catch { }
                return s;
            }

            try {
                XmlSerializer serializer = new XmlSerializer(typeof(Settings));
                using (StreamReader sr = new StreamReader(settingsFilePath)) {
                    s = (Settings)serializer.Deserialize(sr);
                }
            }
            catch {
            }

            return s;
        }

        public bool Save() {
            bool result = false;
            try {
                XmlSerializer x = new XmlSerializer(typeof(Settings));
                using (StreamWriter sw = new StreamWriter(_myFilename)) {
                    x.Serialize(sw, this);
                }
                result = true;
            }
            catch { }
            return result;
        }
    }
}
